package com.bestvike.stone.spring.stream;

import com.bestvike.stone.spring.rabbit.converter.MappingFastJsonRabbitMessageConverter;
import com.bestvike.stone.spring.stream.core.StreamMessageConverterConfigurer;
import com.bestvike.stone.spring.stream.core.StreamMessageHandlerMethodFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.stream.binder.rabbit.config.RabbitMessageChannelBinderConfiguration;
import org.springframework.cloud.stream.binding.MessageConverterConfigurer;
import org.springframework.cloud.stream.config.BindingServiceConfiguration;
import org.springframework.cloud.stream.config.BindingServiceProperties;
import org.springframework.cloud.stream.config.ContentTypeConfiguration;
import org.springframework.cloud.stream.config.SpelExpressionConverterConfiguration;
import org.springframework.cloud.stream.config.SpringIntegrationProperties;
import org.springframework.cloud.stream.converter.CompositeMessageConverterFactory;
import org.springframework.cloud.stream.micrometer.DestinationPublishingMetricsAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Role;
import org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory;

/**
 * Created by 许崇雷 on 2018-09-03.
 */
@Configuration
@EnableConfigurationProperties({BindingServiceProperties.class, SpringIntegrationProperties.class})
@Import({ContentTypeConfiguration.class, DestinationPublishingMetricsAutoConfiguration.class, SpelExpressionConverterConfiguration.class})
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@AutoConfigureBefore(BindingServiceConfiguration.class)
@ConditionalOnClass(RabbitMessageChannelBinderConfiguration.class)
public class StreamRabbitAutoConfiguration {
    @Bean
    MessageHandlerMethodFactory messageHandlerMethodFactory() {
        StreamMessageHandlerMethodFactory messageHandlerMethodFactory = new StreamMessageHandlerMethodFactory();
        messageHandlerMethodFactory.setMessageConverter(new MappingFastJsonRabbitMessageConverter());//设置反序列化转换器,创建 handler 时会使用,参见 StreamMessageHandlerMethodFactory
        messageHandlerMethodFactory.afterPropertiesSet();
        return messageHandlerMethodFactory;
    }

    @Bean
    public MessageConverterConfigurer messageConverterConfigurer(BindingServiceProperties bindingServiceProperties, CompositeMessageConverterFactory compositeMessageConverterFactory) {
        return new StreamMessageConverterConfigurer(bindingServiceProperties, compositeMessageConverterFactory);
    }
}
